package com.example.beiwang;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;

import com.example.beiwang.model.Record;
import com.example.beiwang.tools.CameraUtil;
import com.example.beiwang.tools.DateUtil;
import com.example.beiwang.tools.RecordLab;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;


/**备忘录详情页的控制层*/
public class RecordFragment extends Fragment {
    private static final String ARG_RECORD_ID ="record_id";

    private static final int TAKE_PHOTO =1;
    private static final int TAKE_ALBUM =2;

    private static final int REQUEST_ALBUM_PERMISSION=0;

    private EditText mTitleEditText;
    private EditText mContentEditText;
    private EditText mTextThinkingEditText;
    private CheckBox mCompletedCheckBox;
    private Button mFinishDateButton;

    private ImageView mRecordPicImageView;
    private ImageView mCameraCtrl;
    private ImageView mAlbumCtrl;

    private boolean isCreate;

    private Record mRecord;

    private Uri mImageUri;

    /**由托管的activity来调用，代替new RecordFragment(),因为要传参数*/
    public static RecordFragment newInstance(int recordId){
        RecordFragment recordFragment = new RecordFragment();
        //创建fragment保存键值对的类
        Bundle args = new Bundle();
        //存键值对
        args.putInt(ARG_RECORD_ID,recordId);
        //把键值对的Bundle对象放到fragment
        recordFragment.setArguments(args);
        return recordFragment;
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = getArguments();
        isCreate = args==null?true:false;
        if(isCreate){//说明跳转过来的是新增操作
            mRecord = new Record();
            mRecord.setFinishDate(new Date());
        }else{//说明跳转过来的是更新操作
            int recordId = args.getInt(ARG_RECORD_ID);
            mRecord = RecordLab.getLab(getActivity()).getRecordById(recordId);

        }
    }




    //详情页面
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //参数1：布局的资源id
        //参数2：当前视图的父视图（activity_record.xml）
        //参数3：告诉布局生成器是否将生成的视图添加给父视图，传入false,我们使用代码来添加视图
        View view = inflater.inflate(R.layout.fragment_record, container, false);
        loadRecordTitle(view);
        loadRecordContent(view);
        loadRecordTextThinking(view);
        loadCompletedCheckBox(view);
        loadFinishDateButton(view);
        loadCamera(view);
        loadAlbum(view);
        loadRecordPic(view);
        loadDetailData();
        return view;
    }

    //加载标题控件
    public void loadRecordTitle(View view){
        mTitleEditText = view.findViewById(R.id.record_title);
        mTitleEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mRecord.setTitle(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    //加载内容控件
    public void loadRecordContent(View view){
        mContentEditText = view.findViewById(R.id.record_content);
        mContentEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mRecord.setContent(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    //加载感悟控件
    public void loadRecordTextThinking(View view){
        mTextThinkingEditText = view.findViewById(R.id.record_text_thinking);
        mTextThinkingEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mRecord.setTextThinking(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }


    //加载截止时间按钮控件
    public void loadFinishDateButton(View view){
        mFinishDateButton = view.findViewById(R.id.record_finish_date);
        mFinishDateButton.setText(DateUtil.parseDate(mRecord.getFinishDate()));
        mFinishDateButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
    }

    //加载已完成复选框控件
    public void loadCompletedCheckBox(View view){
        mCompletedCheckBox = view.findViewById(R.id.record_completed);
        mCompletedCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                mRecord.setCompleted(isChecked);

            }
        });
    }





    public void loadCamera(View view){
        mCameraCtrl =  view.findViewById(R.id.record_camera);
        mCameraCtrl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //创建图片的存储路径
                String imageName = String.valueOf(System.currentTimeMillis());
                File storePath = getActivity().getExternalCacheDir();
                File filesDir = getActivity().getFilesDir();
                File cacheDir = getActivity().getCacheDir();
                try {
                    File imageFile = File.createTempFile(imageName, ".jpg", storePath);
                    //在使用该方法之前，需要在AndroidManifest.xml文件中定义共享的规则
                    mImageUri = FileProvider.getUriForFile(getActivity(), "com.example.beiwang.fileprovider", imageFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //启调相机
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT,mImageUri);
                //将图片进行展示
                startActivityForResult(intent,TAKE_PHOTO);
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case TAKE_PHOTO:
                try {
                    Bitmap bitmap = BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(mImageUri));
                    mRecordPicImageView.setImageBitmap(bitmap);
                    mRecordPicImageView.setVisibility(View.VISIBLE);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                break;
            case TAKE_ALBUM:
                Uri uri = data.getData();
                try {
                    Bitmap bitmap  = BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(uri));
                    //加载图片
                    mRecordPicImageView.setImageBitmap(bitmap);
                    //显示展示图片
                    mRecordPicImageView.setVisibility(View.VISIBLE);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            default:
                break;
        }
    }

    public  void loadAlbum(View view){
        mAlbumCtrl =  view.findViewById(R.id.record_album);
        mAlbumCtrl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                //打开相册请求码
                startActivityForResult(intent,TAKE_ALBUM);
            }
        });
    }

    public void loadRecordPic(View view){
        mRecordPicImageView = view.findViewById(R.id.record_pic);
    }




    /**
     * 当是从列表项跳转过来的时侯，执行
     * */
    public void loadDetailData(){
        mTitleEditText.setText(mRecord.getTitle());
        mContentEditText.setText(mRecord.getContent());
        mTextThinkingEditText.setText(mRecord.getTextThinking());
        mCompletedCheckBox.setChecked(mRecord.isCompleted());
        mFinishDateButton.setText(DateUtil.parseDate(mRecord.getFinishDate()));
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if(isCreate){
            RecordLab.getLab(getActivity()).addRecord(mRecord);
        }else{
            mRecord.setFinishDate(new Date());
            RecordLab.getLab(getActivity()).updateRecord(mRecord);
        }

    }
}
